import React, { useState, useRef, useEffect } from 'react'
import { Space, Table, Tag, Modal, Button, message } from 'antd';
import { gethazard } from '@/api/hazard'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import Userfrom from '../../components/userfrom2/index'
import dayjs from 'dayjs'
const Measurementmanagement = () => {
  const { confirm } = Modal
  const [size, setSize] = useState('large');
  const [userdata, setUser] = useState([])
  const [isAddVisible, setisAddVisible] = useState(false)



  const [messageApi, contextHolder] = message.useMessage();

  // const [size, setSize] = useState('large'); // default is 'middle'
  // const { confirm } = Modal
  // const [userdata, setUser] = useState([])
  const [Searchdata, setSearch] = useState([])
  const [deletedata, setdeleteUser] = useState([])
  const [editdata, seteditUser] = useState([])
  const [editid, seteditUserID] = useState([])
  const [adddata, setaddUser] = useState([])
  // 
  const [dataSource, setdataSource] = useState([])
  // const [isAddVisible, setisAddVisible] = useState(false)
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [current, setcurrent] = useState(null)

  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  const AddForm = useRef(null)
  const UpdateForm = useRef(null)



  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '种植地点',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '管理员',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <h3>{text}</h3>,
    },
    {
      title: '新增时间',
      dataIndex: 'birth',
      key: 'birth',
    },
    {
      title: '修改时间',
      dataIndex: 'birth',
      key: 'birth',
    },

    {
      title: "操作",
      render: (item) => {
        return <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} />
          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={() => handleUpdate(item)} />
        </div>
      }
    }
    // {
    //     title: '肾功能',
    //     dataIndex: 'renalfunction',
    //     key: 'renalfunction',
    // },
    // {
    //     title: '血糖',
    //     dataIndex: 'bloodsugar',
    //     key: 'bloodsugar',
    //     render: (text) => <h3>{text} mmol/L</h3>,
    //     sorter: (a, b) => a.bloodsugar - b.bloodsugar,
    // },
    // {
    //     title: '血脂',
    //     dataIndex: 'bloodfat',
    //     key: 'bloodfat',
    //     render: (text) => <h3>{text} mmol/L</h3>,
    //     sorter: (a, b) => a.bloodfat - b.bloodfat,

    // },



  ];

  const showinfo = (item) => {
    console.log(item);
    // setinfo(item)
    // setTimeout(() => {
    // setinfoVisible(true)
    //   console.log(UpdateForm);
    //   // UpdateForm.current.setFieldsValue(item);
    // }, 100);
  }

  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        console.log(item);
        //   console.log('OK');
        // deleteMethod(item)
      },
      onCancel() {
        //   console.log('Cancel');
      },
    });
  }

  const handleUpdate = (item) => {
    setisUpdateVisible(true)
    // console.log(item);
    setTimeout(() => {
      // console.log(item);
      const { birth, id } = item;
      item.birth = dayjs(birth);
      // console.log(item.birth._isAMomentObject);
      // console.log(item);
      setregionList(item.birth);
      seteditUserID(id)
      // console.log(moment(birth, 'YYYY-MM-DD'));
      // console.log(typeof moment(birth, 'YYYY-MM-DD'));

      // var a = ['超级管理员', '管理员', '用户']
      // var b = [
      //     { id: 0, roleName: '女' },
      //     { id: 1, roleName: '男' },
      // ]
      // setregionList(b);
      // var b = ['用户', '管理员', '超级管理员']
      // setregionList(a)
      // setroleList(a)
      UpdateForm.current.setFieldsValue(item);
    }, 100)
    // console.log("dsgsgsgs", UpdateForm);

    setcurrent(item)
  }


  const handleChange = (item) => {
    // item.roleState = !item.roleState
    setdataSource([...dataSource])
  }


  const updateFormOK = () => {
    // console.log(item);
    var a = UpdateForm.current.validateFields().then(value => {
      value.birth = value.birth.format('YYYY-MM-DD');
      var b = userdata.map(v => v.title).indexOf(value.title);
      // console.log(b);
      // var userid = userdata[b].id
      // console.log(userid);
      value.id = editid;
      // console.log(editid);
      // console.log(userdata);
      // console.log(value);
      // var userid = value.title;

      // var b = userdata.filter(v=> v.map(v.title)=value.title)

      // editUser(value).then((response) => {
      //   // console.log(value);
      //   // console.log(response);

      //   getdata()
        message.success('修改成功！')
      // }).catch(e => {
      //   message.error('修改失败！')
      //   // message.success("编辑失败,请重试!")
      // })
      setisUpdateVisible(false)

      setdataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      setisUpdateDisabled(!isUpdateDisabled)


      // }

    })
  }
  const addFormOK = () => {
    AddForm.current.validateFields().then(value => {
      const { birth } = value;
      // var a =new Date(birth)) ;
      // console.log(value);
      // console.log(birth.format('YYYY-MM-DD'));
      value.birth = birth.format('YYYY-MM-DD');
      console.log(value);
      // console.log(moment(value.birth));
      if (userdata.map(v => v.title).indexOf(value.title) != -1) {
        message.error("用户名已存在")
      } else {
        // console.log(userdata.length);
        value.id = ++userdata.length
        setisAddVisible(false)
        // 清空ref
        AddForm.current.resetFields()
          message.success("添加成功!")


      }
    }).catch(err => {
      console.log(err)
    })
  }

  const getdata = async () => {
    let { data: { users } } = await gethazard();
    console.log(users);
    setUser(users)
  }
  useEffect(() => {
    getdata()
  }, [])


  return (
    <div>
      <Button onClick={() => {
        setisAddVisible(true)
      }} type="primary" size={size}>新增</Button>
      <Table columns={columns} dataSource={userdata}
        pagination={{
          pageSize: 6
        }}
        rowKey={item => item.id} />
      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()}
      >
        <Userfrom regionList={regionList} roleList={roleList} ref={UpdateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></Userfrom>
      </Modal>
      <Modal
        open={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false)
        }}
        onOk={() => addFormOK()}
      >
        <Userfrom regionList={regionList} roleList={roleList} ref={AddForm}></Userfrom>
      </Modal>
    </div>
  )
}

export default Measurementmanagement